package www.dianbaozu.com.ui.login

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.dianbaozu.com.extension.save
import www.wen.com.common.lib.base.module.BaseCountDownModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.util.SpUtil


/**
 * @author WEN
 * @Description:注册页面ViewModel
 * @date 2020//25 17:48
 */
class ForgetPasswordViewModel @ViewModelInject constructor(appDataManager: AppDataManager) :
    BaseCountDownModel(appDataManager) {

    /**
     * 验证码注册|登陆
     */
    @FlowPreview
    fun requestResetPassword(
        isForgetOrResetPassword:Boolean,
        body: RequestBodyParameter,
        action: (() -> Unit),
    ) {
        viewModelScope.launch {
            loading.value = UiStateCustom(
                    stateData = LoadingDialog(
                            getString(R.string.verification_code_sending),
                            LoadingDialogStateType.LOADING
                    )
            )
            val result = appDataManager.requestResetPassword(body)
            if (result is Result.Success) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = getString(R.string.reset_successfully),
                                loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                isShowDialogTip = false,
                                isShowToastTip = true,
                                action = action
                        )
                )
                if(isForgetOrResetPassword){
                    SpUtil.save(result.data)
                }
            } else if (result is Result.Error) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = result.exception.message ?:"重置失败",
                                loadingDialogStateType = LoadingDialogStateType.ERROR,
                                isShowDialogTip = false,
                                isShowToastTip = true
                        )
                )
            }
        }
    }


    override fun switchEnabledSubmit(textChange: CharSequence) {
        mEnabledSubmit.value = mPhone.value!!.isNotBlank() &&
                mPhone.value!!.length >= 5 &&
                mVerificationCode.value!!.length >= 4 &&
                mPassWord.value!!.length >= 6
    }
}


